#!/usr/bin/env python3
"""
数据库迁移脚本：添加多图片支持
将DetectionRecord表的image_url和oss_path字段迁移为images_info JSON字段
"""

import asyncio
import json
from tortoise import Tortoise
from src.config.settings import get_settings, get_tortoise_config
from src.models.detection_record import DetectionRecord


async def migrate_to_multi_images():
    """迁移现有数据到多图片格式"""
    settings = get_settings()
    tortoise_config = get_tortoise_config()
    
    # 初始化数据库连接
    await Tortoise.init(config=tortoise_config)
    
    try:
        print("开始迁移DetectionRecord表...")
        
        # 获取所有现有记录
        records = await DetectionRecord.all()
        print(f"找到 {len(records)} 条记录需要迁移")
        
        migrated_count = 0
        for record in records:
            # 检查是否已经是新格式
            if hasattr(record, 'images_info') and record.images_info:
                continue
                
            # 如果有旧的image_url和oss_path，转换为新格式
            if hasattr(record, 'image_url') and record.image_url:
                images_info = [{
                    'imageUrl': record.image_url,
                    'angle': 'top',  # 默认为头顶面
                    'ossPath': getattr(record, 'oss_path', '') or ''
                }]
                
                # 更新记录
                record.images_info = images_info
                await record.save()
                migrated_count += 1
                
                if migrated_count % 100 == 0:
                    print(f"已迁移 {migrated_count} 条记录...")
        
        print(f"迁移完成！共迁移 {migrated_count} 条记录")
        
    except Exception as e:
        print(f"迁移失败: {str(e)}")
        raise
    finally:
        await Tortoise.close_connections()


if __name__ == "__main__":
    asyncio.run(migrate_to_multi_images())